package com.rmc.verifycode.service.web;

import com.rmc.http.accesser.HttpAccesser;
import com.rmc.http.accesser.HttpAccesserParams;
import com.rmc.http.accesser.HttpException;
import com.rmc.verifycode.service.ParseService;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class ParseServiceClient implements ParseService {

	private static Map<String, ParseServiceClient> instanceMap;

	private final String serviceUri;
	private final HttpAccesser accesser;

	private ParseServiceClient(String serviceUri, HttpAccesser accesser) {
		this.serviceUri = serviceUri;
		if (accesser != null) {
			this.accesser = accesser;
		} else {
			HttpAccesserParams params = new HttpAccesserParams();
//			params.setDefaultProxy("http://localhost:8888");
			params.setConnectionsPerRoute(10);
			params.setMaxTotalConnections(50);
			this.accesser = HttpAccesser.createHttpAccesser(params);
		}
	}

	public static ParseServiceClient getInstance(
			String serviceUri) {
		return getInstance(serviceUri, null);
	}

	public static ParseServiceClient getInstance(
			String serviceUri,
			HttpAccesser accesser) {
		if (instanceMap == null) {
			instanceMap = new HashMap<String, ParseServiceClient>();
		}
		ParseServiceClient client = instanceMap.get(serviceUri);
		if (client == null) {
			client = new ParseServiceClient(serviceUri, accesser);
			instanceMap.put(serviceUri, client);
		}
		return client;
	}

	@Override
	public String parse(File image, String id) {
		if (image == null) {
			return "";
		}
		try {
			return accesser.buildReq(serviceUri)
			               .param("id", id).fileParam("image", image).submit();
		} catch (HttpException e) {
			return "";
		}
	}

	public static void main(String[] args) {
		ParseServiceClient client =
				getInstance(
						"http://192.168.1.205:8080/ParseService/ParseService?id=${id}");
		for (int i = 1; i <= 8; i++) {
			File image = new File(
					"f:\\IdeaProjects\\Gather\\verifycode\\src\\test\\resources\\com\\rmc\\verifycode\\"
							+ i + ".bmp");
			String code = client.parse(image, "guizhou.verifycode");
			System.out.println(code);
		}
	}
}
